package com.ipzoe.file.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.ipzoe.common.utils.spring.SpringContextHolder;
import com.ipzoe.file.domain.FileInfoDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.util.Date;

/**
 * 文件工具类
 *
 * @author Eric
 * @date 2020/6/12
 */
@Slf4j
public class FileUtil {

    private FileUtil() {
        throw new IllegalStateException("Utility class");
    }

    public static FileInfoDO getFileInfo(MultipartFile file) {
        //String md5 = fileMd5(file.getInputStream());
        FileInfoDO fileInfo = new FileInfoDO();
        // 将文件的md5设置为文件表的id
        fileInfo.setId(IdUtil.fastSimpleUUID());
        fileInfo.setName(file.getOriginalFilename());
        fileInfo.setContentType(file.getContentType());
        fileInfo.setIsImg(fileInfo.getContentType().startsWith("image/"));
        fileInfo.setSize(file.getSize());
        fileInfo.setCreateTime(new Date());
        return fileInfo;
    }

    /**
     * 文件的md5
     *
     * @param inputStream
     * @return
     */
    public static String fileMd5(InputStream inputStream) {
        return SecureUtil.md5(inputStream);
    }

    public static String saveFile(MultipartFile file, String path) {
        try {
            File targetFile = new File(path);
            if (targetFile.exists()) {
                return path;
            }
            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }
            file.transferTo(targetFile);
            return path;
        } catch (Exception e) {
            log.error("saveFile-error", e);
        }
        return null;
    }

    public static boolean deleteFile(String pathname) {
        File file = new File(pathname);
        if (file.exists()) {
            boolean flag = file.delete();
            if (flag) {
                File[] files = file.getParentFile().listFiles();
                if (files == null || files.length == 0) {
                    file.getParentFile().delete();
                }
            }
            return flag;
        }
        return false;
    }

    /**
     * 生产日期类型的文件目录：floder/year/mm/dd/xxxxxx.xxx
     *
     * @author Eric
     * @date 2020/3/30
     */
    public static String generateDateTypeParentPath(String floder) {
        if (StrUtil.isNotBlank(floder)) {
            //替换“/”“\” 为 File.separator
            floder = floder.replace('/', File.separatorChar);
            floder = floder.replace('\\', File.separatorChar);
            if (floder.endsWith(File.separator)) {
                floder = floder.substring(0, floder.length() - 1);
            }
            if(floder.startsWith(File.separator)){
                floder = floder.substring(1);
            }
        } else {
            floder = "default";
        }

        // 文件按年月日分文件夹存储
        Date today = new Date();
        StringBuilder sb = new StringBuilder(32);
        if(!"pro".equalsIgnoreCase(SpringContextHolder.getApplicationContext().getEnvironment().getActiveProfiles()[0])){
            sb.append("test").append(File.separator);
        }
        sb.append(floder).append(File.separator)
                .append(DateUtil.year(today)).append(File.separator)
                .append(DateUtil.month(today) + 1).append(File.separator)
                .append(DateUtil.dayOfMonth(today)).append(File.separator);
        return sb.toString();
    }

}
